package com.ginmeta.controller.login;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.ginmeta.common.base.AjaxResult;
import com.ginmeta.common.base.BaseController;
import com.ginmeta.domain.login.LoginBody;
import com.ginmeta.domain.login.RegisterBody;
import com.ginmeta.domain.system.entity.SysRole;
import com.ginmeta.domain.system.entity.SysUser;
import com.ginmeta.domain.system.vo.UserInfoRespVO;
import com.ginmeta.service.login.LoginService;
import com.ginmeta.service.system.SysRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 登陆控制层
 *
 * @author GinMeta
 */
@Slf4j
@RequiredArgsConstructor
@RestController
public class LoginController extends BaseController {

    private final LoginService loginService;

    private final SysRoleService sysRoleService;

    /**
     * 登陆api
     *
     * @param loginBody 参数
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody @Validated LoginBody loginBody) {
        // 登陆方法
        loginService.login(loginBody);
        // 返回登陆信息
        return AjaxResult.success(StpUtil.getTokenInfo());
    }

    /**
     * 获取登录用户信息
     *
     * @return 结果
     */
    @GetMapping("/info")
    public AjaxResult getInfo() {
        // 登录用户
        SysUser user = getLoginSysUser();
        // 角色权限
        List<String> roles = StpUtil.getRoleList();
        UserInfoRespVO userVo = JSON.copyTo(user, UserInfoRespVO.class, JSONWriter.Feature.WriteMapNullValue);
        userVo.setRoles(roles);
        if (roles.contains("*")) {
            userVo.setRoleName("超级管理员");
        } else {
            List<SysRole> roleList = sysRoleService.selectRolesByUserId(user.getUserId());
            String roleName = roleList.stream().map(SysRole::getRoleName).collect(Collectors.joining("、"));
            userVo.setRoleName(roleName);
        }
        return AjaxResult.success(userVo);
    }

    /**
     * 退出登陆
     *
     * @return 结果
     */
    @GetMapping("/logout")
    public AjaxResult logout() {
        StpUtil.logout(StpUtil.getLoginId());
        return AjaxResult.success();
    }

    /**
     * 注册接口
     *
     * @param registerBody 注册参数
     * @return 结果
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody @Validated RegisterBody registerBody) {
        // 注册方法
        loginService.register(registerBody);
        // 返回结果
        return AjaxResult.success();
    }
}
